import android.util.Log
import com.google.gson.Gson
import okhttp3.Call
import okhttp3.Callback
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody.Companion.toRequestBody
import okhttp3.Response
import org.json.JSONObject
import java.io.IOException
import java.lang.reflect.Type

object HttpApi {
    private const val BASE_URL = "http://192.168.1.9:8080"
    private val client = OkHttpClient()
    private val gson = Gson()
    private val token =
        "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJiaXJ0aGRheSI6IjIwMjEtMDMtMzIiLCJnZW5kZXIiOiLnlLciLCJzaWduYXR1cmUiOiLkuIDngrnngrnnroDku4siLCJuaWNrbmFtZSI6Iui_t-iMqyIsIm1vYmlsZSI6IjE3MTAyMDM0NTg5IiwiaWQiOjIwLCJhdmF0YXIiOiJodHRwczovL2F2YXRhcnMuZ2l0aHVidXNlcmNvbnRlbnQuY29tL3UvNDQ3NjEzMjEiLCJleHAiOjE3MzQxNDc2NDgsInVzZXJuYW1lIjoiNTI4MTAxNzE5In0.psL66uY91X0QpHq3sVz4fXQxqM8imJ-Nx5sBEgI3dNI"

    data class ApiResponse<T>(
        val code: Int,
        val data: T? = null,
        val message: String? = null
    )


    fun <T> get(
        url: String,
        param: Map<String, Any?>,
        type: Type,
        callback: (ApiResponse<T>?) -> Unit
    ) {
        val urlBuilder = (BASE_URL + url).toHttpUrlOrNull()?.newBuilder()
        for ((key, value) in param) {
            urlBuilder?.addQueryParameter(key, value.toString())
        }
        val urlStr = urlBuilder?.build().toString()
        val request = Request.Builder()
            .url(urlStr)
            .addHeader("token", token)
            .build()

        client.newCall(request).enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                Log.e("HttpApi", "请求失败: ${e.message}")
                callback(null)
            }

            override fun onResponse(call: Call, response: Response) {
                if (response.isSuccessful) {
                    response.body?.let { responseBody ->
                        val json = responseBody.string()
                        try {
                            val res: ApiResponse<T> = gson.fromJson(json, type)
                            callback(res)
                        } catch (e: Exception) {
                            Log.e("HttpApi", "JSON 解析失败: ${e.message}")
                            callback(null)
                        }
                    } ?: callback(null)
                } else {
                    Log.e("HttpApi", "请求失败: ${response.code}")
                    callback(null)
                }
            }
        })
    }

    fun <T> post(
        url: String,
        param: Map<String, Any?>,
        type: Type,
        callback: (ApiResponse<T>?) -> Unit
    ) {
        val jsonObject = JSONObject().apply {
            for ((key, value) in param) {
                put(key, value)
            }
        }
        val requestBody =
            jsonObject.toString().toRequestBody("application/json; charset=utf-8".toMediaType())

        // 构建请求
        val request = Request.Builder()
            .url(BASE_URL + url)
            .addHeader("token", token)
            .post(requestBody)
            .build()

        // 发送请求
        client.newCall(request).enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                Log.e("HttpApi", "请求失败: ${e.message}")
                callback(null)
            }

            override fun onResponse(call: Call, response: Response) {
                if (response.isSuccessful) {
                    response.body?.let { responseBody ->
                        val json = responseBody.string()
                        try {
                            val res: ApiResponse<T> = gson.fromJson(json, type)
                            if (res.code != 1) {
                                Log.d("请求出错", ": ${res.message}")
                            }
                            callback(res)
                        } catch (e: Exception) {
                            Log.e("HttpApi", "JSON 解析失败: ${e.message}")
                            callback(null)
                        }
                    } ?: callback(null)
                } else {
                    Log.e("HttpApi", "请求失败: ${response.code}")
                    callback(null)
                }
            }
        })
    }
}